﻿//课程表(medium): https://leetcode.cn/problems/course-schedule/description/
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int n=numCourses;
        unordered_map<int,vector<int>> edges;
        vector<int> in(n);  //入度
        queue<int> q;
        //建图
        for(auto& e:prerequisites) 
        {
            //b->a
            int a=e[0],b=e[1];
            edges[b].push_back(a);
            in[a]++;
        }
        //将入度为0的加入队列中
        for(int i=0;i<n;i++)
        {
            if(in[i]==0)  q.push(i);
        }
        //开始拓扑排序
        while(q.size())
        {
            int a=q.front(); 
            q.pop();
            for(int x:edges[a])
            {
                in[x]--;
                if(in[x]==0) q.push(x);
            }
        }
        for(auto i:in)
        {
            if(i!=0)  return false;
        }
        return true;
    }
};
//课程表∥(medium): https://leetcode.cn/problems/course-schedule-ii/description/
class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        int n=numCourses;
        unordered_map<int,vector<int>> edges;
        vector<int> in(n);  //入度
        vector<int> ret;
        queue<int> q;
        //建图
        for(auto& e:prerequisites) 
        {
            //b->a
            int a=e[0],b=e[1];
            edges[b].push_back(a);
            in[a]++;
        }
        //将入度为0的加入队列中
        for(int i=0;i<n;i++)
        {
            if(in[i]==0)  q.push(i);
        }
        //开始拓扑排序
        while(q.size())
        {
            int a=q.front(); 
            q.pop();
            ret.push_back(a);
            for(int x:edges[a])
            {
                in[x]--;
                if(in[x]==0) q.push(x);
            }
        }
        for(auto i:in)
        {
            if(i!=0)  return {};
        }
        return ret;
    }
};